package com.kun.kunkunmall.product.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kun.kunkunmall.product.service.CategoryBrandRelationService;
import com.kun.kunkunmall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.utils.PageUtils;
import com.kun.common.utils.Query;

import com.kun.kunkunmall.product.dao.CategoryDao;
import com.kun.kunkunmall.product.entity.CategoryEntity;
import com.kun.kunkunmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查找所有商品分类以及子商品，以树形结构返回
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查找所有商品
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2. 以树形结构返回
        List<CategoryEntity> menus = entities.stream()
                // 找到所有的一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                // 找到一级分类的子分类，并赋值给一级分类的属性“children”
                .peek(categoryEntity -> categoryEntity.setChildren(getChildrens(categoryEntity, entities)))
                // 对一级菜单进行排序
                .sorted((menu1, menu2) -> menu1.getSort() - menu2.getSort()).collect(Collectors.toList());
        return menus;
    }

    /**
     * 删除菜单
     *
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        // 1. 检查该菜单是否被引用
        // TODO
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 查找catelogId的完整路径，供前端回显
     * 格式[父/子/孙]
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return (parentPath.toArray(new Long[parentPath.size()]));
    }

    /**
     * 级联更新所有关联的表
     *
     * @param category
     */
    @Transactional
    @Override
    @Caching(evict = {
            @CacheEvict(value = {"category"},key = "'Level1Categories'"),
            @CacheEvict(value = {"category"},key = "'getCatelogJson'")
    })
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        redisTemplate.delete("catelogJson");
    }

    /**
     * 查询所有一级分类
     * 每一个需要缓存的数据，我们需要指定放到哪个名字的缓存。【缓存的分区（推荐按照业务类型）】
     * springcache的默认行为：1.key自动生成，缓存的名字::SimpleKey[]；2.缓存的value值，默认用jdk序列化；3.默认TTL为-1
     * @return
     */
    @Cacheable(value = {"category"},key = "'Level1Categories'",sync = true) // 代表方法返回结果需要缓存，如果缓存中有，方法不用调用；若缓存中没有，会调用方法，并将结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    @Override
    @Transactional
    @Cacheable(value = {"category"},key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        System.out.println("查询了数据库......");
        // 将数据库的查询变为一次
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 查询所有一级分类
        List<CategoryEntity> level1Categories = getParent_cid(categoryEntities, 0L);
        Map<String, List<Catelog2Vo>> parent_id = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    // 查询每个一级分类的二级分类
                    List<CategoryEntity> category2Entities = getParent_cid(categoryEntities, v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (category2Entities != null) {
                        catelog2Vos = category2Entities.stream().map(c2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, c2.getCatId().toString(), c2.getName());
                            // 查询当前二级分类的三级分类
                            List<CategoryEntity> category3Entities = getParent_cid(categoryEntities, c2.getCatId());
                            if (category3Entities != null) {
                                List<Catelog2Vo.Catelog3Vo> catelog3Vos = category3Entities.stream().map(c3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(c2.getCatId().toString(), c3.getCatId().toString(), c3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(catelog3Vos);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }
        ));
        return parent_id;
    }

    /**
     * 防止堆外内存溢出，（1）升级lettuce客户端；（2）切换使用jedis
     *
     * @return
     */
    @Transactional
    public Map<String, List<Catelog2Vo>> getCatelogJson2() {
        // 从缓存中查询
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        // 缓存中没有
        if (StringUtils.isBlank(catelogJson)) {
            // 从数据库中查询
            Map<String, List<Catelog2Vo>> catelogJsonFromDB = getCatelogJsonFromDBWithRedisLock();
            return catelogJsonFromDB;
        }
        // 缓存中有
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }


    /**
     * 查出所有分类，返回json串
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDB() {
        // TODO 需要使用分布式锁
        synchronized (this) {
            // 得到锁之后需要判断缓存中有没有数据
            return getStringListMap();
        }


    }


    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDBWithRedisLock() {

        // 1.抢占分布式锁
        RLock lock = redissonClient.getLock("catelogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB = null;
        try {
            dataFromDB = getStringListMap();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    private Map<String, List<Catelog2Vo>> getStringListMap() {
        // 得到锁之后需要判断缓存中有没有数据
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (!StringUtils.isBlank(catelogJson)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库......");
        // 将数据库的查询变为一次
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 查询所有一级分类
        List<CategoryEntity> level1Categories = getParent_cid(categoryEntities, 0L);
        Map<String, List<Catelog2Vo>> parent_id = level1Categories.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                v -> {
                    // 查询每个一级分类的二级分类
                    List<CategoryEntity> category2Entities = getParent_cid(categoryEntities, v.getParentCid());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (category2Entities != null) {
                        catelog2Vos = category2Entities.stream().map(c2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, c2.getCatId().toString(), c2.getName());
                            // 查询当前二级分类的三级分类
                            List<CategoryEntity> category3Entities = getParent_cid(categoryEntities, c2.getParentCid());
                            if (category3Entities != null) {
                                List<Catelog2Vo.Catelog3Vo> catelog3Vos = category3Entities.stream().map(c3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(c2.getCatId().toString(), c3.getCatId().toString(), c3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(catelog3Vos);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }
        ));
        // 将数据写入缓存
        String jsonStr = JSONUtil.toJsonStr(parent_id);
        redisTemplate.opsForValue().set("catelogJson", jsonStr);
        return parent_id;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntities, Long parent_cid) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, ArrayList<Long> paths) {
        // 收集当前节点
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 查找当前分类的子分类
     *
     * @param root 当前分类
     * @param all  所有分类
     * @return 当前分类的子分类
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                // 找到当前菜单的所有子菜单
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                // 递归查找
                .peek(categoryEntity -> categoryEntity.setChildren(getChildrens(categoryEntity, all)))
                // 对子菜单进行排序，
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return children;
    }
}